package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private SeckillVoucherServiceImpl seckillVoucherService;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisIdWorker redisIdWorker;

    private IVoucherOrderService proxy;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT=new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //线程池
    private static final ExecutorService SECKILL_ORDER_EXECTOR= Executors.newSingleThreadExecutor();
    //线程任务在此类初始化完成就应该执行
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECTOR.submit(new VoucherOrderHandler());
    }
    //线程任务
    String queueName="stream.orders";
    private class VoucherOrderHandler implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    //1.获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK  2000 STREAMS streams.order >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed()));
                    //2.判断消息是否获取成功
                    if (list==null || list.isEmpty()){
                        //2.1 获取失败说明没有消息 继续下一次循环
                        continue;
                    }
                    //3.解析消息队列中的信息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    //3.获取成功，可以下单
                    handleVoucherOrder(voucherOrder);
                    //4.ACK确认 SACK streams.orders g1 s1
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                    handlePendingList();
                }
            }
        }

//    //阻塞队列
//    private BlockingQueue<VoucherOrder> orderTasks =new ArrayBlockingQueue<>(1024*1024);
//    private class VoucherOrderHandler implements Runnable{
//        @Override
//        public void run() {
//            while (true){
//                //1.获取阻塞队列中的信息
//                try {
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    //2.创建订单
//                    handleVoucherOrder(voucherOrder);
//                } catch (Exception e) {
//                    log.error("处理订单异常",e);
//                }
//            }
//        }

    }
    private void handlePendingList() {
        while (true){
            try {
                //1.获取pending-list 队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1  STREAMS streams.order 0
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create(queueName, ReadOffset.from("0")));

                //2.判断消息是否获取成功
                if (list==null || list.isEmpty()){
                    //2.1 获取失败说明pending-list 没有消息 继续下一次循环
                    break;
                }
                //3.解析消息队列中的信息
                MapRecord<String, Object, Object> record = list.get(0);
                Map<Object, Object> values = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                //3.获取成功，可以下单
                handleVoucherOrder(voucherOrder);
                //4.ACK确认 SACK streams.orders g1 s1
                stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
            } catch (Exception e) {
                log.error("处理pending-list异常",e);
            }
        }

    }

    @Override
    public Result addOrder(Long voucherId) {
        //获取用户
        Long userId = UserHolder.getUser().getId();
        //获取订单id
        long orderId = redisIdWorker.nextId("order");
        //1.执行lua脚本
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId));
        //2.判断结果是否为0
        int r = result.intValue();
        if (r!=0){
            return  Result.fail(r==1? "库存不足":"不能重复下单");
        }
        // 获取锁成功后接着执行这一步   获取代理对象(事务)
         proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }

/*
* 基于阻塞队列实现异步秒杀
* */

//    //获取用户
//    Long userId = UserHolder.getUser().getId();
//    //1.执行lua脚本
//    Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
//            Collections.emptyList(),
//            voucherId.toString(),
//            userId.toString());
//    //2.判断结果是否为0
//    int r = result.intValue();
//        if (r!=0){
//        return  Result.fail(r==1? "库存不足":"不能重复下单");
//    }
//    //2.1 为0 有购买资格 保存到阻塞队列
//    VoucherOrder voucherOrder = new VoucherOrder();
//    long orderId = redisIdWorker.nextId("order");
//    //订单id
//        voucherOrder.setId(redisIdWorker.nextId("order"));
//    //用户id
//        voucherOrder.setUserId(orderId);
//    //代金券id
//        voucherOrder.setVoucherId(voucherId);
//    //保存到阻塞队列
//        orderTasks.add(voucherOrder);
//    // 获取锁成功后接着执行这一步   获取代理对象(事务)
//    proxy = (IVoucherOrderService) AopContext.currentProxy();
//
//        return Result.ok(orderId);
    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        //获取用户
        Long userId = voucherOrder.getUserId();
        //获取锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //调用获取锁的方法
        boolean result = lock.tryLock();
        if (!result){
            log.error("不允许重复下单");
            return;
        }
        try {
             proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }
//    @Override
//    public Result addOrder(Long voucherId) {
//        //查询优惠券
//        SeckillVoucher seckillVoucher = iSeckillVoucherService.getById(voucherId);
//        //获取优惠券开始时间
//        LocalDateTime beginTime = seckillVoucher.getBeginTime();
//        //判断秒杀开始时间
//        if (LocalDateTime.now().isBefore(beginTime)){
//            return Result.fail("秒杀还没开始");
//        }
//        if (LocalDateTime.now().isAfter(seckillVoucher.getEndTime())){
//            return Result.fail("秒杀已经结束");
//        }
//        //获取优惠券库存
//        Integer stock = seckillVoucher.getStock();
//        if (stock<=0){
//            return Result.fail("优惠券已经抢完");
//        }
//        UserDTO user = UserHolder.getUser();
//        Long id = user.getId();
//
//       //获取锁对象
////        SimpleRedisLock redisLock = new SimpleRedisLock("order:" + id, stringRedisTemplate);
//
//        RLock lock = redissonClient.getLock("lock:order:" + id);
//        //调用获取锁的方法
//        boolean result = lock.tryLock();
//        if (!result){
//            return Result.fail("一个用户只允许下一单");
//        }
//        try {
//            // 获取锁成功后接着执行这一步   获取代理对象(事务)
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            lock.unlock();
//        }
//    }
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //判断同一个用户是否已经下过单
        Long userId = voucherOrder.getUserId();
        //根据用户id 和优惠券id在数据库中查询，确保一个用户查询一单
            int count = lambdaQuery().eq(VoucherOrder::getVoucherId, voucherOrder.getVoucherId())
                    .eq(VoucherOrder::getUserId, userId).count();
            if (count > 0) {
                log.error("用户已经购买一次");
            }
            //扣减库存第二种写法   加乐观锁防止超卖问题
            boolean result = seckillVoucherService.update().setSql("stock=stock-1")
                    .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0)
                    .update();
            if (!result) {
                log.error("库存不足");
            }
            save(voucherOrder);
        }
    }

